import CryptoJS from 'crypto-js'

export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

export function setXmStorage(name, value) {
  const jsonStore = value.toString()
  localStorage.setItem(name, CryptoJS.AES.encrypt(jsonStore, 'xmnbzsy'))
}
export function getXmStorage(name) {
  const store = localStorage.getItem(name)
  if (store) {
    return CryptoJS.AES.decrypt(store, 'xmnbzsy').toString(CryptoJS.enc.Utf8)
  } else {
    return ''
  }
}

export function getBgimg() {
  const backdropImg = localStorage.getItem('backdropImg')
  if (backdropImg) {
    return backdropImg
  } 
}

// 颜色16进制转RGB
/**
 * @param {string} 十六进制颜色
 * @returns {Array} rgb三个数字的数组
 */
export function colorRgb(color16) {
  if (!color16) {
    return [24, 145, 255] // 默认半透明颜色
  }
  var sColor = color16.toLowerCase()
  // 十六进制颜色值的正则表达式
  var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
  // 如果是16进制颜色
  if (sColor && reg.test(sColor)) {
    if (sColor.length === 4) {
      var sColorNew = '#'
      for (var i = 1; i < 4; i += 1) {
        sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1))
      }
      sColor = sColorNew
    }
    // 处理六位的颜色值
    var sColorChange = []
    for (var j = 1; j < 7; j += 2) {
      sColorChange.push(parseInt('0x' + sColor.slice(j, j + 2)))
    }
    return sColorChange
  }
  return sColor
}

/**
* 十六进制颜色转化成 15%透明度的颜色
* @param {string} 十六进制颜色 例：#1891ff
* @param {string} 透明度  例：0.15
*/
export function hexToRGBA(hex, opacity = 1) {
  const r = parseInt(hex.slice(1, 3), 16)
  const g = parseInt(hex.slice(3, 5), 16)
  const b = parseInt(hex.slice(5, 7), 16)
  return `rgba(${r}, ${g}, ${b}, ${opacity})`
}
